/*
 * @Description: 电子文件表格
 * @Author: Rfan
 * @Date: 2022-01-25 18:02:15
 * @LastEditTime: 2022-06-22 11:27:58
 */

import { useEffect, useState } from 'react';
import { Button, Space, Table } from 'antd';
import { TableRowSelection } from 'antd/lib/table/interface';
import classNames from 'classnames/bind';
import { displayTitle, showKeysList } from '@/utils/list';

import styles from '../styles/recordTable.module.scss';
import { fetchDownLevelList } from '@/api/archives/archives';

const cx = classNames.bind(styles);

const { Column } = Table;

const ERecordTable = ({ base, query, selectChange }: any) => {
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState([]);
  const [total, setTotal] = useState(0);
  const [fieldList, setFieldList] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [listQuery, setListQuery] = useState<any>({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });

  /**
   * 设置archiveTypeId，一般只首次渲染时触发
   */
  useEffect(() => {
    if (base) {
      setListQuery((state: any) => {
        return {
          ...state,
          param: {
            ...query.param,
            ...base
          }
        };
      });
    }
  }, [base]);

  /**
   * 传入query变化（上级表格选中心条目）更新listQuery
   */
  useEffect(() => {
    if (query && query.length > 0) {
      const [downLevelId, level] = query;
      setListQuery((state: any) => {
        return {
          ...state,
          param: {
            ...state.param,
            downLevelId,
            level
          }
        };
      });
    }
  }, [query]);

  /**
   * listQuery变化请求接口
   */
  useEffect(() => {
    if (listQuery.param?.downLevelId) {
      setLoading(true);
      fetchDownLevelList(listQuery)
        .then((res: any) => {
          const _data = res.data;
          if (_data.totalCount > 0) {
            setList(_data.results?.data || []);
            setTotal(_data.totalCount);
            setFieldList(_data.results?.fields || []);
          }
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  /**
   * @description: 电子文件表格选中相关
   * @param {number[]} selectedKeys
   */
  const onSelectChange = (selectedKeys: number[]) => {
    const _selectedRowKeys = [...selectedRowKeys];
    if (_selectedRowKeys.indexOf(selectedKeys[0]) < 0) {
      setSelectedRowKeys(selectedKeys);
    }
  };
  const rowSelection: TableRowSelection<any> = {
    type: 'radio',
    selectedRowKeys,
    onChange: onSelectChange
  };

  /**
   * @description: 案卷列表选中条目方法
   * @param {any} record 选中的条目
   */
  const selectRow = (record: any) => {
    const _selectedRowKeys = [...selectedRowKeys];
    if (_selectedRowKeys.indexOf(record.id) < 0) {
      setSelectedRowKeys([record.id]);
      selectChange([record.id]);
    }
  };

  return (
    <div className={cx('erecord-table-wrap')}>
      <div className={cx('table-header')}>
        <div className={cx('title')}>电子文件</div>
        <div className={cx('opearte')}>
          <Space>
            <Button disabled>新增</Button>
            <Button disabled>删除</Button>
          </Space>
        </div>
      </div>
      <Table
        dataSource={list}
        loading={loading}
        rowKey="id"
        size="small"
        rowSelection={rowSelection}
        scroll={{ x: 'max-content' }}
        pagination={{
          pageSize: 10,
          total
        }}
        onRow={(record) => ({
          onClick: () => {
            selectRow(record);
          }
        })}
      >
        {showKeysList(list[0], fieldList).map((key) => (
          <Column title={displayTitle(key, fieldList)} dataIndex={key} key={key} align="center" />
        ))}
      </Table>
    </div>
  );
};

export default ERecordTable;
